package com.itcast.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.itcast.pojo.*;
import com.itcast.service.*;
import com.itcast.utils.PoiUtil;
import com.itcast.utils.Respone;
import com.itcast.utils.SaltUtilts;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import sun.rmi.runtime.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2020-06-19
 */
@Controller
@RequestMapping("/admin")
@Slf4j
public class AdminController {
    @Autowired
    private Adminservice adminservice;
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    @Autowired
    private Userservice userservice;
    
    @Autowired
    private Goodsservice goodsservice;

    @Autowired
    private Ordersservice ordersservice;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/index1")
    @ResponseBody
    public Map<String,Object> index() throws JsonProcessingException {
        Map<String, Object> map=new HashMap<>();

        //统计所有用户
        int usercount = userservice.count(null);
        map.put("usercount",usercount);
        log.info("统计所有用户  "+usercount);

        //商品统计
        int goodscount = goodsservice.count(null);
        map.put("goodscount",goodscount);
        log.info("商品统计  "+goodscount);

        //浏览量统计
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.equals("views");
        int viewscount = goodsservice.count(queryWrapper);
        map.put("viewscount",viewscount);
        log.info("浏览量统计  "+viewscount);

        //订单统计
        int ordercount = ordersservice.count(null);
        map.put("ordercount",ordercount);
        log.info("订单统计  "+ordercount);

        //热销
        Map<String, Object> hotSale = ordersservice.hotSale();
        String goodsName = (String) hotSale.get("goodsName");
        QueryWrapper<Goods> queryWrapper1 = new QueryWrapper<>();
        queryWrapper.equals(goodsName);
        Goods hotsale = goodsservice.getOne(queryWrapper1);
        System.out.println(hotsale);
        map.put("hotsale",hotsale);

        return map;
    }

    @GetMapping("/toindex")
    public String toindex(Model model){
        return "admin/index";
    }

    @GetMapping("/toregister")
    public String toregister(){
        return "admin/register";
    }

    @PostMapping("/logins")
    @ResponseBody
    public String login(@RequestBody LoginAdmin loginAdmin, HttpServletRequest request, HttpSession session, Model model) {
        String code1 = (String) session.getAttribute("code");
        try {
            if (loginAdmin.getCaptcha().equals(code1)) {
                //获取主体
                Subject subject = SecurityUtils.getSubject();

                subject.login(new UsernamePasswordToken(loginAdmin.getAdminName(), loginAdmin.getPassword()));


                model.addAttribute("a1", 1);
                model.addAttribute("a2", 2);
                model.addAttribute("a3", 3);
                model.addAttribute("a4", 4);
                model.addAttribute("a5", 5);

                /*//统计所有用户
                int usercount = userservice.count(null);
                model.addAttribute("usercount","usercount");
                log.info("统计所有用户  "+usercount);
                //商品统计
                int goodscount = goodsservice.count(null);
                model.addAttribute("goodscount",goodscount);
                log.info("商品统计  "+goodscount);
                //浏览量统计
                QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
                queryWrapper.equals("views");
                int viewscount = goodsservice.count(queryWrapper);
                model.addAttribute("viewscount",viewscount);
                log.info("浏览量统计  "+viewscount);
                //订单统计
                int ordercount = ordersservice.count(null);
                model.addAttribute("ordercount",ordercount);
                log.info("订单统计  "+ordercount);*/


                model.addAttribute("adminName", loginAdmin.getAdminName());
                request.getSession().setAttribute("adminName", loginAdmin.getAdminName());
                return "ok";
            } else
                {
                    //throw new RuntimeException("验证码错误");
                    return "验证码错误";
            }
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
            return "用户名错误";
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
            return "密码错误";
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return "其他错误";
        }
    }


    @PostMapping("/insertadmin")
    @ResponseBody
    @RequiresRoles("admin")
    public String register(@RequestBody LoginAdmin loginAdmin) {
        String s = redisTemplate.opsForValue().get(loginAdmin.getPhone());

        try {
                Admin admin = new Admin();
                //MD5加密和哈希1024
                SaltUtilts saltUtilts = new SaltUtilts();
                String getdalt = saltUtilts.getdalt(4);
                admin.setSalt(getdalt);
                String password = loginAdmin.getPassword();
                Md5Hash md5Hash = new Md5Hash(password, getdalt, 1024);
                admin.setPassword(md5Hash.toHex());

                admin.setAdminName(loginAdmin.getAdminName());
                Integer state = loginAdmin.getState();
                adminservice.saveOrUpdate(admin);
                if (state==1){
                    Map<String, Integer> map=new HashMap<>();
                    QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
                    queryWrapper.eq("adminName",loginAdmin.getAdminName());
                    Admin adminID = adminservice.getOne(queryWrapper);
                    map.put("userid",adminID.getId());
                    map.put("roleid",2);
                    roleService.insert123(map);
                }else {
                    Map<String, Integer> map=new HashMap<>();
                    QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
                    queryWrapper.eq("adminName",loginAdmin.getAdminName());
                    Admin adminID = adminservice.getOne(queryWrapper);
                    map.put("userid",adminID.getId());
                    map.put("roleid",1);
                    roleService.insert123(map);
                }
                return "ok";
        } catch (Exception e) {
            return "权限不够";
            //e.printStackTrace();
            //e.getMessage();
        }

    }

    @GetMapping("/list")
    @ResponseBody

    public Respone list(@RequestParam("page") int page, @RequestParam("limit") int limit) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        Page<Admin> pageSize = new Page<>(page, limit);
        IPage<Admin> page1 = adminservice.page(pageSize, queryWrapper);
        System.out.println((int) page1.getTotal());
        return new Respone(0, "成功", page1.getRecords(), (int) page1.getTotal());
    }

    @PostMapping("/update")
    @ResponseBody
    public Respone update(@RequestBody Admin admin) {
        admin.setUpdateTime(new Date());
        boolean update = adminservice.updateById(admin);
        if (update) {
            return new Respone(0, "更新成功");
        }
        return new Respone(999, "更新失败");
    }

    @GetMapping("/delete")
    @ResponseBody
    public Respone del(@RequestParam("id") int id) {
        if (adminservice.removeById(id)) {
            return new Respone(0, "删除成功");
        }
        return new Respone(999, "删除失败");
    }

    @PostMapping("/add")
    @ResponseBody
    public Respone add(@RequestBody Admin admin) {
        admin.setCreateDate(new Date());
        boolean save = adminservice.save(admin);
        if (save) {
            return new Respone(0, "添加成功");
        }
        return new Respone(999, "添加失败");
    }

    @RequestMapping("/export")
    @ResponseBody
    public void export(HttpServletResponse response) {
        List<Admin> list = adminservice.list(null);
        PoiUtil.exportExcel(list, "管理员列表", "管理员列表", Admin.class, "管理员列表文件.xls", response);
    }

    @GetMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "go";
    }



}

